<?php

namespace app\admin\controller\auth;

use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use fast\Random;
use fast\Tree;
use think\Db;
use think\Loader;
use think\Validate;

/**
 * 管理员管理
 *
 * @icon   fa fa-users
 * @remark 一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成
 */
class Admin extends Backend
{

    /**
     * @var \app\admin\model\Admin
     */
    protected $model = null;
    protected $selectpageFields = 'id,username,nickname,avatar';
    protected $searchFields = 'id,username,nickname';
    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Admin');

        $this->childrenAdminIds = $this->auth->getChildrenAdminIds($this->auth->isSuperAdmin());
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds($this->auth->isSuperAdmin());

        $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        Tree::instance()->init($groupList);

        $admin = $this->auth->getUserInfo();

        $groupdata = [];
        if ($this->auth->isSuperAdmin()) {
//            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            $result = Db::name('auth_group')->where('id', '<>', 1)->select();
        } else {
            $result = Db::name('auth_group')->whereIn('id', [3, 4])->select();
        }
        foreach ($result as $k => $v) {
            $groupdata[$v['id']] = $v['name'];
        }
        $this->view->assign('groupdata', $groupdata);


        $ruledata = selectMenus_zuzhi2($admin['zuzhi']);
        $this->view->assign('zuzhidata', $ruledata);

        $this->assignconfig("admin", ['id' => $this->auth->id]);
        $this->assign('sex', [0 => '男', 1 => '女']);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $admin = $this->auth->getUserInfo();
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }


            $where1 = "1=1";
            $customWhere = [];
            $filterInfo = $this->request->get('filter','');
            $filterInfo = (array)json_decode($filterInfo, true);
            if(isset($filterInfo['zuzhi'])){
                $op = json_decode($this->request->get("op"),true);
                $zuzhi  = selectMenus_zuzhi2($filterInfo['zuzhi'], 2);
                $where1 .= " and zuzhi in ({$zuzhi}) ";
                unset($filterInfo['zuzhi'],$op['zuzhi']);
                $this->request->get(['filter' => json_encode($filterInfo),'op' => json_encode($op)]);
            }else{
                if (!$this->auth->isSuperAdmin()) {
                    $zuzhi  = selectMenus_zuzhi2($admin['zuzhi'], 2);
                    $where1 .= " and zuzhi in ({$zuzhi}) ";
                }
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->where($where1)
                ->with(['zuzhi','group'])
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => &$v) {
                unset($v['password']);
                unset($v['salt']);
                unset($v['token']);
                //查询所属组织
                $v['groups_text'] = Db::name('auth_group')
                    ->where('id', $v['group']['group_id'])
                    ->value('name');
            }
            unset($v);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    if (!Validate::is($params['password'], '\S{6,30}')) {
                        exception(__("Please input correct password"));
                    }

                    $params['salt']     = Random::alnum();
                    $params['password'] = $this->auth->getEncryptPassword($params['password'], $params['salt']);
                    $params['avatar']   = '/assets/img/avatar.png'; //设置新管理员默认头像。
                    $params['username'] = $params['nickname'];
                    $params['number']   = $this->generateUniqueCodes(1)[0];
                    $nickname = Db::name('admin')->where('nickname',$params['nickname'])->find();
                    if($nickname){
                        return json(['code' => 0, 'msg' => '账号重复']);
                    }
                    $result = $this->model->validate('Admin.add')->save($params);
                    if ($result === false) {
                        exception($this->model->getError());
                    }
                    $group = $this->request->post("group/a");
                    if (!$group) {
                        exception(__('The parent group exceeds permission limit'));
                    }

                    $dataset = [];
                    foreach ($group as $value) {
                        $dataset[] = ['uid' => $this->model->id, 'group_id' => $value];
                    }
                    model('AuthGroupAccess')->saveAll($dataset);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    $nickname = Db::name('admin')->where('nickname',$params['nickname'])->where('id','<>',$ids)->find();
                    if($nickname){
                        return json(['code' => 0, 'msg' => '账号重复']);
                    }
                    if ($params['password']) {
                        if (!Validate::is($params['password'], '\S{6,30}')) {
                            exception(__("Please input correct password"));
                        }
                        $params['salt']     = Random::alnum();
                        $params['password'] = $this->auth->getEncryptPassword($params['password'], $params['salt']);
                    } else {
                        unset($params['password'], $params['salt']);
                    }
                    //这里需要针对username和email做唯一验证
                    $adminValidate = \think\Loader::validate('Admin');
                    $adminValidate->rule([
//                        'username' => 'require|regex:\w{3,30}|unique:admin,username,' . $row->id,
//                        'email'    => 'require|email|unique:admin,email,' . $row->id,
                        'mobile'   => 'regex:1[3-9]\d{9}|unique:admin,mobile,' . $row->id,
                        'password' => 'regex:\S{32}',
                    ]);
                    $params['username'] = $params['nickname'];
                    $result = $row->validate('Admin.edit')->save($params);
                    if ($result === false) {
                        exception($row->getError());
                    }

                    // 先移除所有权限
                    model('AuthGroupAccess')->where('uid', $row->id)->delete();

                    $group = $this->request->post("group/a");


                    $dataset = [];
                    foreach ($group as $value) {
                        $dataset[] = ['uid' => $row->id, 'group_id' => $value];
                    }
                    model('AuthGroupAccess')->saveAll($dataset);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $grouplist = $this->auth->getGroups($row['id']);
        $groupids  = [];
        foreach ($grouplist as $k => $v) {
            $groupids[] = $v['id'];
        }
        $this->view->assign("row", $row);
        $this->view->assign("groupids", $groupids);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");

        if ($ids) {

//            $ids = array_intersect($this->childrenAdminIds, array_filter(explode(',', $ids)));

            $adminList = $this->model->where('id', 'in', $ids)->select();
//            dump($adminList);die;
            if ($adminList) {
                $deleteIds = [];
                foreach ($adminList as $k => $v) {
                    $deleteIds[] = $v->id;
                }
                $deleteIds = array_values(array_diff($deleteIds, [$this->auth->id]));
                if ($deleteIds) {
                    Db::startTrans();
                    try {
                        $this->model->destroy($deleteIds);
                        model('AuthGroupAccess')->where('uid', 'in', $deleteIds)->delete();
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    $this->success();
                }
                $this->error(__('No rows were deleted'));
            }
        }
    }

    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 管理员禁止批量操作
        $this->error();
    }

    /**
     * 下拉搜索
     */
    public function selectpage()
    {
        $this->dataLimit      = 'auth';
        $this->dataLimitField = 'id';
        return parent::selectpage();
    }

    public function generateUniqueCodes($count, $length = 5)
    {
        $codes      = [];
        $characters = '0123456789';
        $maxIndex   = strlen($characters) - 1;

        while (count($codes) < $count) {
            $code = 'GH1';
            for ($i = 0; $i < $length; $i++) {
                $code .= $characters[mt_rand(0, $maxIndex)];
            }
            if (!in_array($code, $codes) && !$this->codeExistsInDb($code)) {
                $codes[] = $code;
            }
        }
        return $codes;
    }

    // 检查编码是否在数据库中存在
    public function codeExistsInDb($code)
    {
        return Db::name('admin')->where('number', $code)->count() > 0;
    }
    public function group_list(){
        $select = DB::name('auth_group')->field('id,name')->select();
        return $select;
    }
}
